/**
 * Copyright 2013 Mani Selvaraj
 * <p/>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p/>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p/>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.shandao.shangxiu.net;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.HttpHeaderParser;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.shandao.shangxiu.util.Constants;
import com.shandao.shangxiu.util.Logger;

/**
 * 上传文件请求
 */
public class MultiPartStringRequest<T> extends Request<T> implements MultiPartRequestInterface {

    private final Listener<T> mListener;
    /* To hold the parameter name and the File to upload */
    private Map<String, File> fileUploads = new HashMap<>();

    /* To hold the parameter name and the string content to upload */
    private Map<String, String> stringUploads = new HashMap<String, String>();
    private Gson gson = new Gson();
    private Class<T> clazz;

    /**
     * Creates a new request with the given method.
     *
     * @param method the request {@link Method} to use
     * @param url URL to fetch the string at
     * @param listener Listener to receive the String response
     * @param errorListener Error listener, or null to ignore errors
     */
    public MultiPartStringRequest(int method, String url, Class<T> clazz, Map<String, File> fileUploads, Map<String, String> stringUploads, Listener<T> listener,
                                  ErrorListener errorListener) {
        super(method, url, errorListener);
        FakeX509TrustManager.allowAllSSL();
        this.clazz = clazz;
        this.fileUploads = fileUploads;
        this.stringUploads = stringUploads;
        if (Constants.IS_DEBUG_MODE) {
            Logger.d("MultiPartStringRequest ---> url", url != null ? url : "NULL");
        }
        mListener = listener;
    }


    public void addFileUpload(String param, File file) {
        fileUploads.put(param, file);
    }

    public void addStringUpload(String param, String content) {
        stringUploads.put(param, content);
    }

    /**
     * 要上传的文件
     */
    public Map<String, File> getFileUploads() {
        if (Constants.IS_DEBUG_MODE) {
            Logger.d("MultiPartStringRequest ---> FileUpload", fileUploads != null ? fileUploads.toString() : "NULL");
        }
        return fileUploads;
    }

    /**
     * 要上传的参数
     */
    public Map<String, String> getStringUploads() {
        if (Constants.IS_DEBUG_MODE) {
            Logger.d("MultiPartStringRequest ---> BODY", stringUploads != null ? stringUploads.toString() : "NULL");
        }
        return stringUploads;
    }


    @Override
    protected Response<T> parseNetworkResponse(NetworkResponse response) {
        try {
            String json = new String(response.data, "UTF-8");
            if (Constants.IS_DEBUG_MODE) {
                Logger.d(" RESPONSE", json);
            }
            return Response.success(gson.fromJson(json, clazz), HttpHeaderParser
                    .parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            Logger.d("MultiPartStringRequest ---> error",e.toString());
            return Response.error(new ParseError(e));
        } catch (JsonSyntaxException e) {
            Logger.d("MultiPartStringRequest ---> error",e.toString());
            return Response.error(new ParseError(e));
        }
    }

    @Override
    protected void deliverResponse(T response) {
        if (mListener != null) {
            mListener.onResponse(response);
        }
    }

    /**
     * 空表示不上传
     */
    public String getBodyContentType() {
        return null;
    }
}